package study.source.sunghun.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.View;

import study.source.sunghun.dao.dbviewer.DatabaseViewerDAO;
import study.source.sunghun.service.dbviewer.DatabaseViewerService;
import study.source.sunghun.vo.dbviewer.ColumnInfo;

@Controller
@RequestMapping("/dbviewer")
public class DatabaseViewerController {
	private static Logger logger = LoggerFactory.getLogger(DatabaseViewerController.class);
	
	@Autowired
	private DatabaseViewerDAO dbViewer;
	
	@Autowired
	private View jsonView;
	
	@Autowired 
	DatabaseViewerService service;
	

	/**
	 * Data Viewer Main Page Init Data
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/main")
	public String viewerMain(HttpServletRequest request) throws Exception {
		logger.debug("========= Main ==========");
		
		List<String> tableList = dbViewer.getTableList();		
		request.setAttribute("tableList", tableList);
		
		return "sunghun/dbviewer/viewerMain";
	}
	
	/**
	 * Get Column Infomation
	 * 
	 * @param request
	 * @param tableName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/columnInfo")
	public View getColumnInfo(ModelMap modelMap,
			@RequestParam String tableName)throws Exception {
		logger.debug("========= getColumnInfo ==========");
		
		List<ColumnInfo> columnInfoList = dbViewer.getColumnInfo(tableName);
		modelMap.addAttribute(columnInfoList);
		
		return jsonView;
	}
	
	/**
	 * Excute Query
	 * 
	 * @param modelMap
	 * @param query
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/excute", method = RequestMethod.POST)
	public View excuteQuery(ModelMap modelMap,
			@RequestParam String query) throws Exception {		
		
		modelMap.addAllAttributes(service.excuteQuery(query));
		
		return jsonView;
	}
}






